package com.example.weibo_suhuanzhen.activities;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.OnLifecycleEvent;

import com.example.weibo_suhuanzhen.LoginEvent;
import com.example.weibo_suhuanzhen.R;
import com.example.weibo_suhuanzhen.UserSession;
import com.example.weibo_suhuanzhen.bean.BaseBean;
import com.example.weibo_suhuanzhen.retrofit.ShzApi;
import com.example.weibo_suhuanzhen.retrofit.RetrofitManager;
import com.example.weibo_suhuanzhen.sharedPreferences.SharedPreferencesManager;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tvSend;
    final int totalSecondCount = 60;
    final String TAG = "login";
    private EditText et_phoneNumber;
    private EditText et_code;
    private TextView login_btn;
    private TextView back;
    private SharedPreferencesManager preferences;

    int currentSecond = totalSecondCount;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);
        initView();

        // Register the lifecycle observer
        getLifecycle().addObserver(new MyLifecycleObserver(handler));
    }

    private void initView() {
        tvSend = findViewById(R.id.send);
        et_phoneNumber = findViewById(R.id.phone_num);
        et_code = findViewById(R.id.code);
        login_btn = findViewById(R.id.login_btn);
        back = findViewById(R.id.back);
        login_btn.setClickable(false);
        login_btn.setEnabled(false);  // 初始化为不可点击

        tvSend.setOnClickListener(this);
        login_btn.setOnClickListener(this);
        back.setOnClickListener(this);
        preferences = SharedPreferencesManager.getInstance(this);
        if (!Objects.equals(preferences.getData("phoneNumber", ""), "")) {
            et_phoneNumber.setText(preferences.getData("phoneNumber", ""));
        }
        et_phoneNumber.addTextChangedListener(textWatcher);
        et_code.addTextChangedListener(textWatcher);
    }

    private final TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {}

        @Override
        public void afterTextChanged(Editable s) {
            validateInputs();
        }
    };

    private void validateInputs() {
        String phoneNumber = et_phoneNumber.getText().toString().trim();
        String code = et_code.getText().toString().trim();
        boolean isPhoneNumberValid = phoneNumber.length() == 11;
        boolean isCodeValid = code.length() == 6;

        if (isPhoneNumberValid && isCodeValid) {
            login_btn.setClickable(true);
            login_btn.setEnabled(true);
            login_btn.setBackgroundResource(R.drawable.round_button_1);
        } else {
            login_btn.setClickable(false);
            login_btn.setEnabled(false);
            login_btn.setBackgroundResource(R.drawable.round_button);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send: {
                String phoneNumber = et_phoneNumber.getText().toString().trim();
                if (phoneNumber.length() == 11) {
                    SharedPreferencesManager instance = SharedPreferencesManager.getInstance(LoginActivity.this);
                    instance.saveData("phoneNumber", phoneNumber);
                    sendMessage(phoneNumber);
                    countDown();
                } else {
                    Toast.makeText(this, "输入正确手机号", Toast.LENGTH_SHORT).show();
                }
                break;
            }
            case R.id.login_btn: {
                String phoneNumber = et_phoneNumber.getText().toString().trim();
                String code = et_code.getText().toString().trim();
                login(phoneNumber, code);
                Log.d(TAG, "onClick: 登录" + UserSession.getInstance().isLoggedIn());
                break;
            }
            case R.id.back: {
                finish();
                break;
            }
        }
    }

    private static class MyHandler extends Handler {
        private final WeakReference<LoginActivity> mActivity;

        MyHandler(LoginActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            LoginActivity activity = mActivity.get();
            if (activity != null) {
                switch (msg.what) {
                    case 100:
                        int second = (int) msg.obj;
                        activity.tvSend.setText(second + "s");
                        activity.tvSend.setEnabled(false);
                        if (activity.currentSecond != 0) {
                            Message message = Message.obtain();
                            message.what = 100;
                            message.obj = --activity.currentSecond;
                            sendMessageDelayed(message, 1000);
                        } else {
                            activity.tvSend.setEnabled(true);
                            activity.tvSend.setText("重新发送");
                            activity.currentSecond = activity.totalSecondCount;
                        }
                        break;
                }
            }
        }
    }

    private final MyHandler handler = new MyHandler(this);

    private void countDown() {
        Message obtain = Message.obtain();
        obtain.what = 100;
        obtain.obj = currentSecond;
        handler.sendMessageDelayed(obtain, 1000);
    }

    private void sendMessage(String phoneNumber) {
        ShzApi shzApi = RetrofitManager.getInstance().createApi();
        ShzApi.PhoneRequest phoneRequest = new ShzApi.PhoneRequest(phoneNumber);
        shzApi.sendMsgCode(phoneRequest).enqueue(new Callback<BaseBean<Object>>() {
            @Override
            public void onResponse(Call<BaseBean<Object>> call, Response<BaseBean<Object>> response) {
                tvSend.setText(currentSecond + "s");
                Message message = new Message();
                message.what = 100;
                message.obj = currentSecond;

                // 在发送消息之前移除之前可能存在的延迟消息
                handler.removeMessages(100);

                handler.sendMessageDelayed(message, 1000);
                handler.post(() -> {
                    assert response.body() != null;
                    Toast.makeText(getApplicationContext(), response.body().msg, Toast.LENGTH_SHORT).show();
                });
                System.out.println(response.body());
            }

            @Override
            public void onFailure(Call<BaseBean<Object>> call, Throwable throwable) {
                System.out.println("--->onFailure");
            }
        });
    }

    private void login(String phoneNumber, String code) {
        ShzApi api = RetrofitManager.getInstance().createApi();
        Call<ShzApi.LoginResponse> call = api.verifyCode(new ShzApi.LoginRequest(phoneNumber, code));
        call.enqueue(new Callback<ShzApi.LoginResponse>() {
            @Override
            public void onResponse(Call<ShzApi.LoginResponse> call, Response<ShzApi.LoginResponse> response) {
                if (response.isSuccessful() && response.body() != null && response.body().getCode() == 200) {
                    String token = response.body().getData();
                    preferences.saveData("token", token);
                    preferences.saveBoolean("isLoggedIn", true);
                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    // 跳转到主页面
                    EventBus.getDefault().post(new LoginEvent()); // 发送登录事件
                    setResult(RESULT_OK);
                    UserSession.getInstance().setLoggedIn(true);
                    finish();
                } else {
                    Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ShzApi.LoginResponse> call, Throwable t) {
                Toast.makeText(LoginActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

    // LifecycleObserver to remove handler messages on destroy
    public static class MyLifecycleObserver implements LifecycleObserver {
        private final Handler handler;

        public MyLifecycleObserver(Handler handler) {
            this.handler = handler;
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        public void onDestroy() {
            handler.removeCallbacksAndMessages(null);
        }
    }
}
